package com.example.ymm.modules1.service.impl.sys.iot;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.my.sys.iot.IotTag;
import com.example.ymm.modules1.entity.my.sys.iot.IotTimeLog;
import com.example.ymm.modules1.mapper.my.sys.IotTimeLogMapper;
import com.example.ymm.modules1.query.sys.iot.IotTagQueryCriteria;
import com.example.ymm.modules1.query.sys.iot.IotTimeLogQueryCriteria;
import com.example.ymm.modules1.service.sys.iot.IotMsLogService;
import com.example.ymm.modules1.service.sys.iot.IotTagService;
import com.example.ymm.modules1.service.sys.iot.IotTimeLogService;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.RedisUtil;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.*;

@Service
@DSTransactional
@DS("slave2")
@Slf4j
public class IotTimeLogServiceImpl extends BaseServiceImpl<IotTimeLogMapper, IotTimeLog> implements IotTimeLogService {


    @Value("${spring.profiles.active}")
    String PD_MATCH;
    @Autowired
    IotTagService iotTagService;

    @Autowired
    IotMsLogService iotMsLogService;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public TableList<IotTimeLog> list(IotTimeLogQueryCriteria criteria, YmPageDto pageDto) {
        IPage<IotTimeLog> page = new Page<IotTimeLog>(pageDto.getPage(),pageDto.getPageSize());
        QueryWrapper predicate = QueryHelpPlus.getPredicate(IotTimeLog.class, criteria);
//        predicate.orderByAsc("sort");
        baseMapper.selectPage(page, predicate);
        TableList<IotTimeLog> tableList=new TableList(page);
        return tableList;
    }
    
    public List<IotTimeLog> queryAll(IotTimeLogQueryCriteria criteria) {
        List<IotTimeLog> result =baseMapper.selectList(QueryHelpPlus.getPredicate(IotTimeLog.class, criteria));
        return result;
    }


    @Override
    public void scheduledTaskClose() {
        Set<String> keys = redisUtil.keys("tag_open:*");
        for (String key : keys) {
            String id = redisUtil.getString(key);
            System.out.println("--定时运行关灯time_id:"+id);
            IotTimeLog timeLog = getById(id);
            if(UtilValidate.isNotEmpty(timeLog)){
                if(timeLog.getStatus().equals(0)){
                    redisUtil.remove(key);
                }else{
                    Date endTime = timeLog.getEndTime();
                    Date nowTime = new Date();
                    if(nowTime.after(endTime)){

                        String requestSend = timeLog.getRequestSend();
                        JSONObject jsonObject1 = JSONObject.parseObject(requestSend);
                        JSONArray jsonArray = jsonObject1.getJSONArray("tagMacs");
                        List<String> noCloseMac = new ArrayList<>();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            String no=jsonArray.getString(i);
                            noCloseMac.add(no);
                        }
                        IotTagQueryCriteria criteria = new IotTagQueryCriteria();
                        criteria.setStatus(1);
                        criteria.setTagMacIn(noCloseMac);

                        if(UtilValidate.isNotEmpty(noCloseMac)){
                            List<IotTag> iotTags = iotTagService.queryAll(criteria);
                            List<String> sends = new ArrayList<>();
                            for (IotTag iotTag : iotTags) {
                                sends.add(iotTag.getTagMac());
                            }
                            log.info("--sends:"+sends);
                            if(UtilValidate.isNotEmpty(sends)){
                                String locationName=null;
                                if("库区2".equals(timeLog.getType())){
                                    locationName= "配件2区";
                                }else{
                                    locationName= "配件1区";
                                }

                                JSONObject jsonObject = iotTagService.closeTagBatch(sends,locationName);
                                if(jsonObject.getIntValue("code")==200){
                                    timeLog.setStatus(0);
                                    saveOrUpdate(timeLog);
                                    redisUtil.remove(key);
                                }else{
                                    log.error("--定时关闭失败");
                                }
                            }else{
                                timeLog.setStatus(0);
                                saveOrUpdate(timeLog);
                                redisUtil.remove(key);
                            }
                        }else{
                            timeLog.setStatus(0);
                            saveOrUpdate(timeLog);
                            redisUtil.remove(key);
                        }


                        //可以关灯了
//                        IotTimeLogQueryCriteria criteria = new IotTimeLogQueryCriteria();
//                        criteria.setId(id);
//                        List<String> noCloseMac = getNoCloseMac(criteria);
//
//                        if(UtilValidate.isNotEmpty(noCloseMac)){
//                            List<IotTag> xiandaoDengs = iotTagService.findXiandaoDengByTagMacIn(noCloseMac);
//                            List<String> xd_tagMacIn=new ArrayList<>();
//                            for (IotTag iotTag : xiandaoDengs) {
//                                xd_tagMacIn.add(iotTag.getTagMac());
//                            }
//                            if(UtilValidate.isNotEmpty(xd_tagMacIn)){
//                                noCloseMac.addAll(xd_tagMacIn);
//                            }
//                            log.info("--未关闭mac noCloseMac:"+noCloseMac);
//                            log.info("---定时关闭的巷道灯:"+xd_tagMacIn);
//                            if(UtilValidate.isNotEmpty(noCloseMac)){
//                                JSONObject jsonObject = iotTagService.closeTag(String.join(",", noCloseMac));
//                                if(jsonObject.getIntValue("code")==200){
//                                    timeLog.setStatus(0);
//                                    saveOrUpdate(timeLog);
//                                    redisUtil.remove(key);
//                                }else{
//                                    log.error("--定时关闭失败");
//                                }
//                            }else{
//                                timeLog.setStatus(0);
//                                saveOrUpdate(timeLog);
//                                redisUtil.remove(key);
//                            }
//                        }

                    }
                }
            }else{
                redisUtil.remove(key);
            }
        }
    }


    @Override
    public List<String> getNoCloseMac(IotTimeLogQueryCriteria criteria) {
        return baseMapper.getNoCloseMac(criteria);
    }

    @Override
    public void cleanLogs() {
        iotMsLogService.remove(null);
        remove(null);
        Set<String> keys1 = redisUtil.keys("tag_open:*");
        for (String key : keys1) {
            redisUtil.remove(key);
        }
        Set<String> keys2 = redisUtil.keys("outOrder:*");
        for (String key : keys2) {
            redisUtil.remove(key);
        }
        Set<String> keys3 = redisUtil.keys("stock:*");
        for (String key : keys3) {
            redisUtil.remove(key);
        }
        Set<String> keys4 = redisUtil.keys("close_tag:*");
        for (String key : keys4) {
            redisUtil.remove(key);
        }
        Set<String> keys5 = redisUtil.keys("c_xd_tah:*");
        for (String key : keys5) {
            redisUtil.remove(key);
        }

    }
}
